import CryptoJS, { lib } from 'crypto-js';
import Env from './env'

// AES 加密
export function encryptAES(data: string): string {
    const key: CryptoJS.lib.WordArray = CryptoJS.enc.Utf8.parse(Env.encryptAESKey);
    const iv: CryptoJS.lib.WordArray = CryptoJS.enc.Utf8.parse(Env.encryptAESIv);
    const ciphertext: lib.CipherParams = CryptoJS.AES.encrypt(data, key, {
        iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    });
    return ciphertext.ciphertext.toString(CryptoJS.enc.Hex);
}

// AES 解密
export function decryptAES(data: string): string {
    const key: CryptoJS.lib.WordArray = CryptoJS.enc.Utf8.parse(Env.decryptAESKey);
    const iv: CryptoJS.lib.WordArray = CryptoJS.enc.Utf8.parse(Env.decryptAESIv);
    let _data = CryptoJS.enc.Hex.parse(data);
    let srcs = CryptoJS.enc.Base64.stringify(_data);
    const decrypted: lib.WordArray = CryptoJS.AES.decrypt(srcs, 
    key, {
        iv,
        mode: CryptoJS.mode.CBC,
        padding: CryptoJS.pad.Pkcs7
    });
    return decrypted.toString(CryptoJS.enc.Utf8);
}
